# -*- conding:UTF-8 -*-

'''
@ Project: cloudnews
@ File: mysql_To_Es.py
@ Author: 罗婷
@ Date：2022/7/1 15:32

'''


# 把数据库数据导入索引
import pymysql
from elasticsearch import Elasticsearch


def get_mysql_data(table_name):
    """获取指定表的全部数据"""
    client = pymysql.connect(host="127.0.0.1", port=3306,
                             user="root", password="password", db='sjk616')
    sql = 'select * from %s' % table_name
    # 创建游标
    course = client.cursor()
    # 执行sql语句
    course.execute(sql)
    # 查询全部
    rest = course.fetchall()
    # 关闭连接
    course.close()
    return rest


def into_es(table_name):
    """把数据导入es"""
    es = Elasticsearch(hosts="http://82.156.35.108:9200/")
    rest = get_mysql_data(table_name)
    print('rest>>', rest)
    # 把数据库中数据写入es
    # 先清空指定表的索引
    restul = es.indices.exists(index=table_name)
    if restul:
        es.indices.delete(index=table_name)
    for i in rest:
        print(i)
        try:
            #     id '课程id')
            #     course_name 课程名')
            #     course_status doc='0即将上线1已上线')
            #     course_img doc='课程封面')
            #     course_introduce  doc='课程介绍')
            #     learner  doc='学习人数')
            #     course_type   doc='课程类别')
            #     attention    doc='关注人数')
            #     is_collect    doc='是否关注')

            es.index(index=table_name, document={
                'table_name': table_name,
                'id': i[0],
                'course_name': i[1],
                'course_status': i[2],
                'course_img': i[3],
                'course_introduce': i[4],
                'learner': i[5],
                'course_type': i[6],
                'attention': i[7],
                'is_collect': i[8],
            })
        except Exception as e:
            print("es 创建索引错误, 原因是", e)


if __name__ == '__main__':
    into_es('tb_course')